package cn.skcks.springboot03.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyHandlerInterceptor implements HandlerInterceptor {
	// preHandle：在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制、权限校验等处理
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getParameter("token");
		System.out.println("token => " + token);

		HttpSession session = request.getSession();

		if(!request.getServletPath().equals("/intercepter")){
			session.removeAttribute("intercepter");
		}

		if (request.getServletPath().equals("/test-intercepter")) {
			request.setAttribute("msg","Intercepter");
			session.setAttribute("intercepter","Intercepter Session");
			request.getRequestDispatcher("/intercepter").forward(request,response);
			return false;
		}

		return true;
	}

	// postHandle：在业务处理器处理请求执行完成后，生成视图之前执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	// afterCompletion：在DispatcherServlet完全处理完请求后被调用，可用于清理资源等
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}
}